import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 5000
})

// 请求拦截器
service.interceptors.request.use(
  (config) => {
    // console.log('token:', store.getters.token)
    // 非空时 携带token
    const _token = store.getters.token
    if (_token) {
      config.headers.Authorization = `Bearer ${_token}`
    }
    // 携带token
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截
service.interceptors.response.use(
  (response) => {
    // console.log(response)
    const { data, message, success } = response.data
    if (!success) {
      Message.error(message)
      return Promise.reject(new Error(message))
    } else {
      return data
    }
  },
  (error) => {
    return Promise.reject(error)
  }
)

export default service
